<template>
  <div>
    <a-card>
      <a-form ref="modifyPriceForm" :model="couponData" :style="{ width: '100%' }" layout="horizontal" auto-label-width>
        <div class="base-info-item">
          <h4>基本信息</h4>
          <div class="form-item-view">
            <a-form-item field="promotionName" label="活动名称" :rules="[REQUIRED]">
              <a-input :disabled="disabled" v-model="couponData.promotionName" allow-clear :style="{ width: '260px' }" />
            </a-form-item>
            <a-form-item field="couponName" label="优惠券名称" :rules="[REQUIRED]">
              <a-input :disabled="disabled" v-model="couponData.couponName" allow-clear :style="{ width: '260px' }" />
            </a-form-item>
            <a-form-item field="couponType" label="优惠券类型">
              <a-select :style="{ width: '260px' }" v-model="couponData.couponType" :disabled="disabled">
                <a-option v-for="item of couponType" :value="item.value" :label="item.label" :key="item.value" />
              </a-select>
            </a-form-item>
            <a-form-item field="couponDiscount" label="折扣" v-if="couponData.couponType == 'DISCOUNT'">
              <a-input :disabled="disabled" v-model="couponData.couponDiscount" allow-clear :style="{ width: '260px' }" />
              <span class="describe">请输入0-10之间数字,可以输入一位小数</span>
            </a-form-item>
            <a-form-item field="price" label="面额" v-if="couponData.couponType == 'PRICE'" :rules="[REQUIRED]">
              <a-input :disabled="disabled" v-model="couponData.price" allow-clear :style="{ width: '260px' }" />
            </a-form-item>
            <a-form-item field="getType" label="活动类型">
              <a-select :style="{ width: '260px' }" v-model="couponData.getType" :disabled="disabled">
                <a-option v-for="item of activityType" :value="item.value" :label="item.label" :key="item.value" />
              </a-select>
            </a-form-item>
            <a-form-item field="storeCommission" label="店铺承担比例">
              <a-input :disabled="disabled" v-model="couponData.storeCommission" allow-clear :style="{ width: '260px' }">
                <template #append><span>%</span></template>
              </a-input>
              <span class="describe">店铺承担比例,输入0-100之间数值</span>
            </a-form-item>
            <a-form-item field="publishNum" label="发放数量" v-if="couponData.getType === 'FREE'" :rules="[REQUIRED]">
              <a-input :disabled="disabled" v-model="couponData.publishNum" allow-clear :style="{ width: '260px' }" />
              <div class="tips">如果发放数量为0时,则代表不限制发放数量</div>
            </a-form-item>
            <a-form-item field="couponLimitNum" label="领取数量限制" v-if="couponData.getType === 'FREE'" :rules="[REQUIRED]">
              <a-input :disabled="disabled" v-model="couponData.couponLimitNum" allow-clear :style="{ width: '260px' }" />
              <div class="tips">如果领取数量为0时,则代表不限制领取数量</div>
            </a-form-item>
            <a-form-item field="description" label="范围描述" :disabled="disabled" :rules="[REQUIRED]">
              <a-textarea allow-clear style="width: 260px" :max-length="50" show-word-limit v-model="couponData.description" />
            </a-form-item>
          </div>
          <h4>使用限制</h4>
          <div class="form-item-view">
            <a-form-item field="consumeThreshold" label="消费门槛" :rules="[REQUIRED]">
              <a-input :disabled="disabled" v-model="couponData.consumeThreshold" allow-clear :style="{ width: '260px' }" />
            </a-form-item>
            <a-form-item field="rangeTime" label="有效期">
              <a-radio-group v-model="rangeTimeType">
                <a-radio :disabled="disabled" :value="1" v-if="couponData.getType !== 'ACTIVITY'">起止时间</a-radio>
                <a-radio :disabled="disabled" :value="0" v-if="couponData.getType === 'ACTIVITY'">固定时间</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item field="rangeTime" label="有效期" v-if="rangeTimeType === 1" :rules="[REQUIRED]">
              <a-range-picker style="width: 254px;" v-model="couponData.rangeTime" :disabled="disabled" />
            </a-form-item>
            <a-form-item field="effectiveDays" label="有效期" v-if="rangeTimeType === 0" :rules="[REQUIRED]">
              <a-input-number v-model="couponData.effectiveDays" :style="{ width: '260px' }" class="input-demo" :min="1" :max="365" :disabled="disabled" />
              <span class="describe">领取当天开始几天内有效(1-365间的整数)</span>
            </a-form-item>
            <a-form-item field="scopeType" label="使用范围">
              <a-radio-group v-model="couponData.scopeType" type="button" :disabled="disabled">
                <a-radio value="ALL"> 全品类 </a-radio>
                <a-radio value="PORTION_GOODS"> 指定商品 </a-radio>
                <a-radio value="PORTION_GOODS_CATEGORY"> 部分商品分类 </a-radio>
              </a-radio-group>
            </a-form-item>
            <!--指定商品-->
            <a-form-item v-if="couponData.scopeType == 'PORTION_GOODS'">
              <div style="display: flex; margin-bottom: 10px">
                <a-button :disabled="disabled" type="outline"  @click="openSkuList">选择商品</a-button>
                <a-button :disabled="disabled" style="margin-left: 10px" 
                  @click="delSelectGoods" type="outline" status="danger">批量删除</a-button>
              </div>
            </a-form-item>
            <a-form-item v-if="couponData.scopeType == 'PORTION_GOODS'">
              <PickTablePage :columns="columns" :methods="methods" :dataList="couponData.promotionGoodsList" :checkbox="true" :bordered="true"
                         :defaultSelectedKeys="selectedKeys" @selectionChanges="(val) => {selectedKeys = val}" :enablePagination="false">
                <template #operation="{ rowIndex }">
                  <a-button type="text" status="danger" @click="delGoods(rowIndex)" :disabled="disabled">删除</a-button>
                </template>
              </PickTablePage>
            </a-form-item>
            <!--部分商品分类-->
            <a-form-item v-if="couponData.scopeType == 'PORTION_GOODS_CATEGORY'">
              <a-cascader :options="goodsCategoryList" :style="{ width: '260px' }" :disabled="disabled"
                v-model:model-value="couponData.scopeIdGoods" allow-clear :path-mode="true" />
            </a-form-item>
          </div>
        </div>
      </a-form>
      <a-button style="margin-right: 5px" @click="closeCurrentPage">返回</a-button>
      <a-button :disabled="disabled" type="primary"  @click="handleSubmit">提交</a-button>
    </a-card>
    <skuselect ref="skuSelect" @change="changSkuList" :goodsOrSku="true" :defaultGoodsSelectedList="couponData.promotionGoodsList"></skuselect>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, watch } from "vue"
import { PickTablePage } from '@pickmall/ui-v3-components'
import skuselect from '@/components/goods-sku-selector/index.vue';
import { Message } from '@arco-design/web-vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { getCategoryTree, savePlatformCoupon, getPlatformCoupon,editShopCoupon, getGoodsSkuData } from '@/api/goods';
import { useRouter, useRoute } from 'vue-router';
import { dayFormatHHssMM, unixToDate, unitDatePickerEndTime } from '@/utils/filters';
import { REQUIRED, VARCHAR20 } from '@/utils/validator';
import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';

const router = useRouter();
const route = useRoute();
const rangeTimeType = ref<number>(1);  // 当前时间类型
const goodsCategoryList = ref([]) as any; // 商品分类列表
const modifyPriceForm = ref();

// 表格的行选择器配置
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: true
});
const selectedKeys = ref([]);
const pagination = { pageSize: 100 };
// 表格
const columns = [
  {
    title: '商品名称',
    dataIndex: 'goodsName',
    // width: 300
  },
  {
    title: '商品价格',
    dataIndex: 'price',
    // width: 300
  },
  {
    title: '库存',
    dataIndex: 'quantity',
    // width: 300
  },
  // {
  //   title: '操作',
  //   slotName: 'Optiona'
  // },
];
const methods :MethodsRule = {
  title: '操作',
  width: 250,
  fixed: 'right',
  methods: [
    {title: '操作', slot: true, slotTemplate: 'operation'}
  ]
};
//  获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
const skuSelect = ref(null) as any; // 商品选择器
const disabled = ref(route.query.onlyView) as any;
const rowkey = ref([]); // 所选行key
const couponData = ref({
  /** 店铺承担比例 */
  storeCommission: 0,
  /** 发行数量 */
  publishNum: 0,
  /** 运费承担者 */
  scopeType: "ALL",
  /** 限领数量 */
  couponLimitNum: 1,
  /** 活动类型 */
  couponType: "PRICE",
  /** 优惠券名称 */
  couponName: "",
  promotionName: "",
  getType: "FREE",
  promotionGoodsList: [
    // goodsName: '',
    // price: '',
    // quantity: '',
    // originalPrice: '',
    // storeId: '',
    // storeName: '',
    // skuId: '',
    // categoryPath: '',
    // thumbnail: '',
    // goodsType: '',
    // goodsId: '',
    // originPrice: '',
  ],
  scopeIdGoods: [],
  rangeDayType: "",
  couponDiscount: '',
  price: '',
  description: '',
  consumeThreshold: '',
  rangeTime: '',
  effectiveDays: 1
}) as any
// 优惠券类型
const couponType = [
  {
    value: 'DISCOUNT',
    label: '打折'
  },
  {
    value: 'PRICE',
    label: '减免现金'
  },
]
// 活动类型
const activityType = [
  {
    value: 'FREE',
    label: '免费领取'
  },
  {
    value: 'ACTIVITY',
    label: '活动赠送'
  },
]
// 打开商品选择器
const openSkuList = () => {
  skuSelect.value.modalData.visible = true
}
// 商品选择器数据
const changSkuList = (val: any) => {
  couponData.value.promotionGoodsList = [];
  val.forEach((e: any) => {
    couponData.value.promotionGoodsList.push({
      goodsName: e.goodsName,
      price: e.price,
      originalPrice: e.price,
      quantity: e.quantity,
      storeId: e.storeId,
      sellerName: e.sellerName,
      skuId: e.id,
      id: e.id
    })
    // couponData.value.promotionGoodsList.push({
    //   goodsName: e.goodsName,
    //   price: e.price,
    //   quantity: e.quantity,
    //   originalPrice: e.price,
    //   storeId: e.storeId,
    //   storeName: e.storeName,
    //   skuId: e.id,
    //   categoryPath: e.categoryPath,
    //   thumbnail: e.small,
    //   goodsType: e.goodsType,
    //   goodsId: e.goodsId,
    //   originPrice: e.price,
    //   id: e.skuId,
    // })
  });
  couponData.value.promotionGoodsList = couponData.value.promotionGoodsList.map((v: any, index: any) => {
    return {
      ...v,
      key: index + 1
    }
  })
};
// 多选删除商品
const delSelectGoods = () => {
  if (selectedKeys.value.length === 0) {
    Message.warning('您还未选择要删除的数据！');
    return;
  }
  const res = JSON.parse(JSON.stringify(selectedKeys.value));

  modal.confirm({
    title: '确认删除',
    content: '您确认要删除所选商品吗?',
    alignCenter: false,
    onOk: () => {
      couponData.value.promotionGoodsList = couponData.value.promotionGoodsList.filter((item: any) => {
        return !res.includes(item.skuId);
      });
    },
  });
};
const filterCategoryId = (list: any, idArr: any) => {
  // 递归获取分类id
  list.forEach((e: any) => {
    if (e instanceof Array) {
      filterCategoryId(e, idArr);
    }
    if (!Array.isArray(e)) {
      if (!idArr.includes(e)) {
        idArr.push(e);
      }
    }
  });
  return idArr;
};
// 返回上一页
const routerpreviousPage = () => {
  router.push({ name: 'coupon' })
};
// 删除表格数据
const delGoods = (idx: any) => {
  couponData.value.promotionGoodsList.splice(idx, 1)
};
// 选择行
const selectTableChanges = (record: any) => {
  // console.log(record, 'val');
  // rowkey.value.push(...val)
};
// 返回
const closeCurrentPage = () => {
  routerpreviousPage()
};
// 提交
const handleSubmit = async () => {
  const auth = await modifyPriceForm.value?.validate();
  if (!auth) {
    const params = JSON.parse(JSON.stringify(couponData.value));
    // 判断当前活动类型
    params.getType != "ACTIVITY" ? delete params.effectiveDays : 1;
    if (rangeTimeType.value === 1) {
      params.rangeDayType = "FIXEDTIME";
      // params.startTime = dayFormatHHssMM(couponData.value.rangeTime[0]);
      // params.endTime = dayFormatHHssMM(couponData.value.rangeTime[1]);
      const {startTime, endTime} = unitDatePickerEndTime(couponData.value.rangeTime);
      params.startTime = startTime;
      params.endTime = endTime;
    } else {
      params.rangeDayType = "DYNAMICTIME";
      delete params.rangeTime;
    }
    let scopeId = [] as any;
    if (params.scopeType == "PORTION_GOODS" && (!params.promotionGoodsList || params.promotionGoodsList.length == 0)) {
      Message.warning('请选择指定商品');
      return;
    }
    if (params.scopeType == "PORTION_GOODS_CATEGORY" && (!params.scopeIdGoods || params.scopeIdGoods.length == 0)) {
      Message.warning('请选择商品分类');
      return;
    }
    if (params.scopeType != "PORTION_GOODS_CATEGORY") {
      delete params.scopeIdGoods;
    }
    if (params.scopeType == "PORTION_GOODS") {
      // 指定商品
      params.promotionGoodsList = params.promotionGoodsList.map((item: any) => {
        scopeId.push(item.skuId);
        const temp = {
          goodsName: item.goodsName,
          originalPrice: item.originalPrice,
          price: item.price,
          quantity: item.quantity,
          skuId: item.skuId,
          storeId: item.storeId,
        };
        return temp;
      });
      params.scopeId = scopeId.toString();


    } else if (params.scopeType == "ALL") {
      delete params.promotionGoodsList;
    } else if (params.scopeType == "PORTION_GOODS_CATEGORY") {
      // 部分商品分类
      scopeId = filterCategoryId(params.scopeIdGoods, []);
      params.scopeId = scopeId.toString();
      delete params.promotionGoodsList;
    }
    delete params.scopeIdGoods;
    if (!route.query.id) {
      delete params.id;
      savePlatformCoupon(params).then((res: any) => {
        if (res.data.success) {
          Message.success('优惠券发送成功');
          routerpreviousPage()
        }
      })
    } else {
      delete params.consumeLimit;
      delete params.updateTime;
      editShopCoupon(params).then((res)=> {
        if(res.data.success){
          Message.success("优惠券修改成功");
          routerpreviousPage()
        }
      })
    }
  }
};
// 获取分类列表数据
const getCagetoryList = async () => {
  const res = await getCategoryTree();
  if (res.data.success) {
    goodsCategoryList.value = res.data.result;
    goodsCategoryList.value = goodsCategoryList.value.map((item: any) => {
      if (item.children && item.children.length) {
        item.children = item.children.map((child: any) => {
          if (child.children) {
            child.children = child.children.map((son: any) => {
              return {
                value: son.id,
                label: son.name,
              };
            });
          } else {
            child.children = null;
          }
          return {
            value: child.id,
            label: child.name,
            children: child.children || null,
          };
        });
      } else {
        item.children = null;
      }
      return { value: item.id, label: item.name, children: item.children };
    })
  }
}
// 获取单个优惠券
const getCoupon = async () => {
  const res = await getPlatformCoupon(route.query.id);
  if (res.data.success) {
    const data: any = res.data.result;
    couponData.value = res.data.result;
    if (couponData.value.scopeId) {
      couponData.value.scopeIdGoods = couponData.value.scopeId.split(',')
      // couponData.value.scopeIdGoods = couponData.value.scopeId.split(',').length === 3?couponData.value.scopeId.split(','):[];
    }
    if (data.startTime && data.endTime) {
      couponData.value.rangeTime = [unixToDate(Number(new Date(data.startTime))/1000, 'yyyy-MM-dd'), unixToDate(Number(new Date(data.endTime))/1000, 'yyyy-MM-dd')];
    }


    if (!data.promotionGoodsList) data.promotionGoodsList = [];
    rangeTimeType.value = data.rangeDayType === "DYNAMICTIME" ? 0 : 1;
    // if (data.scopeType == "PORTION_GOODS_CATEGORY") {
    //   const prevCascader = data.scopeId.split(",");
    //   function next(params, prev) {
    //     for (let i = 0; i < params.length; i++) {
    //       const item = params[i];
    //       if (item.children) {
    //         next(item.children, [...prev, item]);
    //       } else {
    //         if (prevCascader.includes(item.id)) {
    //           prevCascader = prevCascader.map((key) => {
    //             if (key === item.id) {
    //               let result = prev.map((item) => item.id);

    //               return [...result, item.id];
    //             } else {
    //               return key;
    //             }
    //           });
    //         } else {
    //           i === params.length - 1 && (prev = []);
    //         }
    //       }
    //     }
    //   }
    // }
  }
}
onMounted(async () => {
  getCagetoryList()
  if (route.query.id) {
    getCoupon()
  }
})

watch(() => couponData.value.getType, (val) => {
  if (val == "FREE") {
    rangeTimeType.value = 1;
  }else{
    rangeTimeType.value = 0;
  }
  if(rangeTimeType.value == 0){
    delete couponData.value.rangeTime
  }
}, { deep: true, immediate: true })
</script>

<style lang="less" scoped>
h4 {
  margin-bottom: 10px;
  padding: 0 10px;
  border: 1px solid #ddd;
  background-color: #f8f8f8;
  font-weight: bold;
  color: #333;
  font-size: 14px;
  line-height: 40px;
  text-align: left;
}

.describe {
  font-size: 12px;
  margin-left: 10px;
  color: #999;
}

.effectiveDays {
  font-size: 12px;
  color: #999;

  >* {
    margin: 0 4px;
  }
}

.tips {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}
</style>
